import $http from './http'

class Login {
  static miniLogin(code, appId, pathPre, callback) {
    const miniLoginUrl = pathPre ? pathPre + '/miniLogin' : 'miniLogin'
    return new Promise((resolve, reject) => $http.post(miniLoginUrl, {
      code,
      appId
    }).then((data) => {
      // 保存本地token,返回对应的数据
      Login.setLocal(data.resultData)
      console.log('login result', data)
      if (callback && typeof callback === 'function') {
        callback('success')
      }
      return resolve(data)
    }).catch(err => {
      if (callback && typeof callback === 'function') {
        callback('error')
      }
      reject(err)
    }))
  }

  static setLocal(resultData) {
    const localData = {
      resultData,
      time: new Date().getTime()
    }
    wx.setStorageSync(Login.tokenCode, localData)
  }

  static hasLogin(milis) {
    return new Promise((resolve, reject) => {
      Login.checkLogin(resolve, reject, 1, milis)
    })
  }

  static checkLogin(resolve, reject, times, milis) {
    if (!milis) {
      milis = 500
    }
    if (times > 10) {
      console.warn('5s 中没有获取到登录信息，需要处理次异常，比如刷新页面')
      reject('error,5s 内没有获取到登录信息内容')
    } else {
      const resultData = Login.getFromLocal()
      console.log('第', times, '次获取内容..')
      if (resultData) {
        console.log('获取到了数据', resultData)
        resolve(resultData)
      } else {
        setTimeout(() => {
          Login.checkLogin(resolve, reject, times + 1)
        }, milis)
      }
    }
  }

  static getFromLocal() {
    const localData = wx.getStorageSync(Login.tokenCode)
    if (!localData) {
      return false
    }
    try {
      if (new Date().getTime() - localData.time > 2 * 60 * 60 * 1000) {
        wx.removeStorageSync(Login.tokenCode)
        return false
      }
      localData.time = new Date().getTime()
      wx.setStorageSync(Login.tokenCode, localData)
      return localData.resultData
    } catch (e) {
      return false
    }
  }
}

Login.tokenCode = 'mini-app-wdt-user'

export default Login
